﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Threading;

namespace 工厂模式.抽象工厂.SqlHelper
{
    public class DefaultCache<T> : ICache<T>
    {
        private static DefaultCache<T> Instance;
        private Dictionary<string, T> parms=new Dictionary<string,T>();
        private ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();
        private static object locker = new object();

        private DefaultCache()
        {
           
        }

        public static DefaultCache<T> GetInstance()
        {
            if (Instance != null) return Instance;
            lock (locker)
            {
                if (Instance == null)
                    Instance = new DefaultCache<T>();
            }
            return Instance;
        }

        /// <summary>
        /// 缓存参数对象
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="name">参数名</param>
        /// <param name="parm">参数对象</param>
        public void Insert(string connectionString, string name, T parm)
        {
            readerWriterLock.EnterWriteLock();
            parms.Add(string.Concat(connectionString, "_", name), parm);
            readerWriterLock.ExitWriteLock();
        }
        /// <summary>
        /// 移除参数对象
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="name"></param>
        public void Remove(string connectionString, string name)
        {
            readerWriterLock.EnterWriteLock();
            parms.Remove(string.Concat(connectionString, "_", name));
            readerWriterLock.ExitWriteLock();
        }
        /// <summary>
        /// 获得参数对象
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="name">参数名</param>
        /// <returns></returns>
        public T GetParameter(string connectionString, string name)
        {
            readerWriterLock.EnterReadLock();
            T parm = parms[string.Concat(connectionString, "_", name)];
            readerWriterLock.ExitReadLock();
            return parm;
        }
    }
}
